package com.centerm.eterm.ui.tool;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.SwingUtilities;

public class BusyNow
{
	private static Popup	mypopup		= null;
	private static JLabel	label		= null;
	private static BusyNow	instance	= null;

	private BusyNow(final String str)
	{
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				URL url = this.getClass().getResource("/img/blue-loading.gif");
				ImageIcon image = new ImageIcon(url);
				image.setImage(image.getImage().getScaledInstance(36, 36, Image.SCALE_DEFAULT));

				label = new JLabel(str, image, JLabel.LEFT);
				label.setPreferredSize(new Dimension(230, 40));
				label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
				label.setBackground(Color.white);
				label.setOpaque(true);

				Toolkit kit = Toolkit.getDefaultToolkit();
				Dimension screenSize = kit.getScreenSize();
				int width = screenSize.width;
				int height = screenSize.height;
				int x = (width - 100) / 2;
				int y = (height - 20) / 2;
				mypopup = PopupFactory.getSharedInstance().getPopup(null, label, x, y);
			}
		});
	}

	public static BusyNow GetInstanceAndShow(final String str)
	{
		if (null == instance)
		{
			instance = new BusyNow(str);
		}
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{
				if (!label.isShowing())
				{
					Toolkit kit = Toolkit.getDefaultToolkit();
					Dimension screenSize = kit.getScreenSize();
					int width = screenSize.width;
					int height = screenSize.height;
					int x = (width - 100) / 2;
					int y = (height - 20) / 2;
					label.setText(str);
					mypopup = PopupFactory.getSharedInstance().getPopup(null, label, x, y);
					mypopup.show();
				}
			}
		});
		return instance;
	}

	public static BusyNow GetInstance()
	{
		return instance;
	}

	public void SetIdle()
	{
		SwingUtilities.invokeLater(new Runnable()
		{
			public void run()
			{

				mypopup.hide();
			}
		});
	}
}
